package cn.kgc.service.impl;

import cn.kgc.mapper.EmpMapper;
import cn.kgc.pojo.Emp;
import cn.kgc.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class EmpServiceImpl implements EmpService {

    @Resource
    private EmpMapper empMapper;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public Object getEmpById(Integer id) {
        String key = "emp:"+ id;
        //从缓存拿数据,没有则查数据库
        Object emp = redisTemplate.opsForValue().get(key);
        if(emp==null){
            synchronized (this){
                emp = redisTemplate.opsForValue().get(key);
                if(emp==null){
                    log.debug("--------->查数据库");
                    emp= empMapper.getEmpById(id);
                    redisTemplate.opsForValue().set(key,emp);
                }else{
                    log.debug("----------------------->查缓存2");
                }

            }

        }else{
            log.debug("----------------------->查缓存");
        }

        return emp;
    }
}
